/**
 * Created by ptt on 2016/5/27/0027.
 */
define([], function () {
    if (!map) {
        var projection = ol.proj.get('EPSG:3857');
        var projectionExtent = projection.getExtent();
        var size = ol.extent.getWidth(projectionExtent) / 256;
        var resolutions = new Array();
        var matrixIds = new Array();
        for (var z = 0; z < 18; ++z) {
            resolutions[z] = size / Math.pow(2, z);
            matrixIds[z] = 'EPSG:900913:' + z;
        }
        //GIST 基础地图资源
        var source_reproduction = new ol.source.WMTS({
            url: mapURL.gistBaseMapurl,
            matrixSet: 'EPSG:900913',
            format: 'image/png',
            projection: projection,
            layer: "vector",
            tileGrid: new ol.tilegrid.WMTS({
                origin: ol.extent.getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds
            }),
            tileLoadFunction: function (imageTile, src) {
                var index = src.indexOf("?");
                var hash = src.slice(index).toUpperCase();
                imageTile.getImage().src = src.slice(0, index) + hash;

            },
            style: 'default',
            wrapX: true
        });

        var tile_loading = 0, tile_loaded = 0,flag = true;
        source_reproduction.on("tileloadstart", function (e) {
            ++tile_loading;
            if (flag) {
                Message_bone.trigger("infoStart");
                flag = false;
            }
        });
        source_reproduction.on("tileloadend", function (e) {
            ++tile_loaded;
            if (tile_loading === tile_loaded) {
                Message_bone.trigger("infoEnd");
                flag = true;
            }
        });
         //加载行政区划WMS
        var Districtssource = new ol.source.TileWMS({
            url: queryConfig.queryDistricts.url,
            params: {
                LAYERS:  queryConfig.queryDistricts.layers,
                STYLES: '',
                format: 'image/png',
                tiled: true,
                transparent: true,
                VERSION: "1.1.1",
                SRS: "EPSG:900913"
            },
            crossOrigin:"anonymous"
        });
        var Districtslayer = new ol.layer.Tile({
            source: Districtssource
        });
        map = new ol.Map({
            layers: [
                new ol.layer.Tile({
                    opacity: 1,
                    source: source_reproduction,
                    extent:ol.proj.transformExtent([112.6920,21.2389,115.6737,24.0274],'EPSG:4326', 'EPSG:3857')
                }),
                Districtslayer
            ],
            target: "map-map",
            renderer:"canvas",
            logo: false,
            controls: [
                new ol.control.Zoom({
                target: "map-zoom",
                duration: 600
            }),
                new ol.control.ScaleLine({
                    target:"map-scaleline"
                })
            ],
            view: new ol.View({
                center: ol.proj.transform([114.156, 22.614], 'EPSG:4326', 'EPSG:3857'),
                zoom: 11,
                extent:ol.proj.transformExtent([113.6920,22.2389,114.6737,23.0274],'EPSG:4326', 'EPSG:3857'),
                projection: 'EPSG:3857',
                maxZoom:18,
                minZoom:7
            })
        });
        ol.Map.prototype.addSubjectLayer=function(pLayer,removeKey)
        {
            //先根据条件移除图层
            if(removeKey)
            {
                for(var mapLayer in this.getLayers()){
                        if(mapLayer.getKeys().indexOf("layerName")>0){
                            if(mapLayer.get("layerName")==removeKey){this.removeLayer(mapLayer);}
                        }
                }
            }
            if(pLayer&&pLayer instanceof  ol.layer){
                this.addLayer(pLayer);
            }
        }
        //地图查询符号
        var wfsimage = new ol.style.Icon({
            src: '/ssjc/images/gis/marker.png',
            scale: 0.8
        });
        var wfsstyle = {
            'Point': new ol.style.Style({
                image: wfsimage
            }),
            'MultiPoint': new ol.style.Style({
                image: wfsimage
            }),
            'LineString': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: '#00FFFF',
                    width: 3
                })
            }),
            'MultiLineString': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: '#00FFFF',
                    width: 3
                })
            }),
            'Polygon': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: '#00FFFF',
                    lineDash: [4],
                    width: 3
                }),
                fill: new ol.style.Fill({
                    color: 'rgba(0, 0, 255, 0.1)'
                })
            }),
            'MultiPolygon': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: '#00FFFF',
                    lineDash: [4],
                    width: 3
                }),
                fill: new ol.style.Fill({
                    color: 'rgba(0, 0, 255, 0.1)'
                })
            })
        };
        function styleFunction(feature){
            return wfsstyle[feature.getGeometry().getType()];
        };
        //根据道路编码查询道路，并进行道路定位
        var roadCode = $('#roadCode').val();
        if(roadCode){
            queryToLocation(roadCode);
        }
         function queryToLocation (roadCode) {
            if(roadCode){
               var source = new ol.source.Vector();
               var layer = new ol.layer.Vector({
                    source: source,
                    style:styleFunction
                });
                var f = ol.format.ogc.filter;
                var featureRequest = new ol.format.WFS().writeGetFeature({
                    srsName: 'EPSG:4326',
                    featureNS: queryConfig.queryRoad.featureNS,
                    featurePrefix: queryConfig.queryRoad.featurePrefix,
                    featureTypes: queryConfig.queryRoad.layers,
                    outputFormat: 'application/json',
                    filter: f.equalTo(queryConfig.queryRoad.queryFieldName, roadCode)
                });
                // post请求，并根据请求的数据进行加载
                fetch(queryConfig.queryRoad.url, {
                    method: 'POST',
                    body: new XMLSerializer().serializeToString(featureRequest)
                }).then(function(response) {
                    return response.json();
                }).then(function(json) {
                    var features = new ol.format.GeoJSON().readFeatures(json,{featureProjection: 'EPSG:3857',dataProjection:"EPSG:4326"});
                    if(features.length>0) {
                        source.addFeatures(features);
                        map.getView().fit(source.getExtent(), (map.getSize()));
                    }
                });
                map.addLayer(layer);
            }
        };
        Message_bone.on("addStyle", function (e, data) {
            var mp = {
                "disease":"道路病害",
                "roadFit":"道路保养",
                "repair":"道路小修",
                "":""
            };
            var LAYERS = data.value["selector"] ? data.query + '_' + data.value["selector"]
                : data.query;
            var s = data.roadName && "roadName=" + data.roadName;
            LAYERS += data.roadName && data.phase !== "养护" ? s : data.phase === "养护" ? s + "&" + "beginTime=" + 2013 : "";
            if (data.roadName) {
                data.query && $.ajax({
                    url: LAYERS
                }).then(function (response) {
                    response = response[0] || response;
                    var features;
                    var json = response.geoJson ? JSON.parse(JSON.stringify(response.geoJson)) : response;
                    if (data.phase !== "养护") {
                        var startY = parseInt(response['starttime']) || 2014,
                            endY = parseInt(response['endtime']) || 2014,
                            startM = response['starttime'] && parseInt(response['starttime'].slice(5, 7)) || 5,
                            endM = response['endtime'] && parseInt(response['endtime'].slice(5, 7)) || 9,
                            numM;
                        features = response && new ol.format.GeoJSON().readFeatures(json, {featureProjection: 'EPSG:4326'});
                    } else {
                        features = response && new ol.format.GeoJSON().readFeatures(json, {featureProjection: 'EPSG:3857'});
                    }
                    var y = [];
                    var image = new ol.style.Icon({
                        src: "/ssjc/images/gis/marker.png",
                        scale: 0.8
                    });
                    var hightLightStyles = {
                        'Point': new ol.style.Style({
                            image: image
                        }),
                        'LineString': new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'red',
                                width: 4
                            })
                        }),
                        'MultiLineString': new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'blue',
                                width: 4
                            })
                        }),
                        'Polygon': new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'green',
                                lineDash: [4],
                                width: 4
                            }),
                            fill: new ol.style.Fill({
                                color: 'rgba(0, 0, 255, 0.1)'
                            })
                        })
                    };
                    var HightLightstyleFunction = function(feature) {
                        if (feature.getProperties().type) {
                            var imgDisease = feature.getProperties().type === "disease" && new ol.style.Icon({
                                    src: "/ssjc/images/gis/disease.png",
                                    scale: 0.8
                                });
                            var imgroadFit = feature.getProperties().type === "roadFit" && new ol.style.Icon({
                                    src: "/ssjc/images/gis/maintain.png",
                                    scale: 0.8
                                });
                            var imgrepair = feature.getProperties().type === "repair" && new ol.style.Icon({
                                    src: "/ssjc/images/gis/minorrepair.png",
                                    scale: 0.8
                                });
                            var styles = {
                                'disease': new ol.style.Style({
                                    image: imgDisease
                                }),
                                'roadFit': new ol.style.Style({
                                    image: imgroadFit
                                }),
                                'repair': new ol.style.Style({
                                    image: imgrepair
                                })
                            };
                        }
                        return feature.getProperties().type ? styles[feature.getProperties().type] : hightLightStyles[feature.getGeometry().getType()];
                    };
                    var source = new ol.source.Vector();
                    var layer = new ol.layer.Vector({
                        source: source,
                        style: HightLightstyleFunction
                    });
                    data.that._all = source;
                    source.addFeatures(features);
                    if (data.phase === '前期') {
                        numM = endY - startY === 0 ? endM - startM : (endY - startY) * 12 + endM;
                        data.that._E = layer;
                    } else if (data.phase === '施工') {
                        numM = endY - startY === 0 ? endM - startM : (endY - startY) * 12 + endM;
                        data.that.yanghuTime = response['endtime'];
                        data.that._Ex = layer;
                    } else {
                        startY = data.that.yanghuTime && parseInt(data.that.yanghuTime) || 2015;
                        endY = new Date().getFullYear();
                        startM = data.that.yanghuTime && parseInt(data.that.yanghuTime.slice(5, 7)) || 1;
                        endM = new Date().getMonth();
                        numM = endY - startY === 0 ? endM - startM : (endY - startY) * 12 + endM;
                        data.that._M = layer;
                    }
                    var height = numM * 30;
                    var h = 0;
                    var idx = 0;
                    data.that._test = {};
                    for (var k = startY; k <= endY; k += 1) {
                        var j = startM, mon = [], _test = {};
                        if (data.phase !== "养护") {

                            if (numM < 12) {
                                while (j < endM) {
                                    j += 1;
                                    mon.push(j);
                                }
                            } else {
                                while (j < 12) {
                                    j += 1;
                                    mon.push(j);
                                }
                                numM -= 12;
                                startM = 1;
                            }
                            _height = mon.length * 30;
                            y.push({
                                year: k,
                                month: mon,
                                height: _height || 120,
                                startLayout: idx === 0 ? h : h + 50
                            });
                            h += y[idx] && y[idx].height || 0;
                        } else {
                            var i, len, dis = 0, rep = 0, fit = 0, text = [];
                            for (i = 0, len = features.length; i < len; i += 1) {
                                var type = features[i].getProperties()['type'];
                                var time = features[i].getProperties()['foundTime'] || features[i].getProperties()['fitTime'];
                                if (k == parseInt(time) && !(parseInt(time.slice(5, 7)) in _test)) {
                                    mon.push(parseInt(time.slice(5, 7)));
                                    text[parseInt(time.slice(5, 7))] = {};
                                    _test[parseInt(time.slice(5, 7))] = {};
                                    _test[parseInt(time.slice(5, 7))].features = [];
                                    _test[parseInt(time.slice(5, 7))].features.push(features[i]);
                                    switch (type) {
                                        case "disease": {
                                            if (!text[parseInt(time.slice(5, 7))].dis) text[parseInt(time.slice(5, 7))].dis = 0;
                                            text[parseInt(time.slice(5, 7))].dis += 1;
                                            break;
                                        }
                                        case "roadFit": {
                                            if (!text[parseInt(time.slice(5, 7))].fit) text[parseInt(time.slice(5, 7))].fit = 0;
                                            text[parseInt(time.slice(5, 7))].fit += 1;
                                            break;
                                        }
                                        case "repair": {
                                            if (!text[parseInt(time.slice(5, 7))].rep) text[parseInt(time.slice(5, 7))].rep = 0;
                                            text[parseInt(time.slice(5, 7))].rep += 1;
                                            break;
                                        }
                                        default: break;
                                    }
                                    text[parseInt(time.slice(5, 7))].text = '<p>道路小修：' + text[parseInt(time.slice(5, 7))].rep + '处</p><p>道路保养：' + text[parseInt(time.slice(5, 7))].fit + '处</p>'
                                        + '<p>道路病害：' + text[parseInt(time.slice(5, 7))].dis + '处</p>';
                                } else if (parseInt(time.slice(5, 7)) in _test) {
                                    switch (type) {
                                        case "disease": {
                                            if (!text[parseInt(time.slice(5, 7))].dis) text[parseInt(time.slice(5, 7))].dis = 0;
                                            text[parseInt(time.slice(5, 7))].dis += 1;
                                            break;
                                        }
                                        case "roadFit": {
                                            if (!text[parseInt(time.slice(5, 7))].fit) text[parseInt(time.slice(5, 7))].fit = 0;
                                            text[parseInt(time.slice(5, 7))].fit += 1;
                                            break;
                                        }
                                        case "repair": {
                                            if (!text[parseInt(time.slice(5, 7))].rep) text[parseInt(time.slice(5, 7))].rep = 0;
                                            text[parseInt(time.slice(5, 7))].rep += 1;
                                            break;
                                        }
                                        default: break;
                                    }
                                    text[parseInt(time.slice(5, 7))].text = '<p>时间：'
                                        + k + '年' + parseInt(time.slice(5, 7)) + '月</p>'
                                        + '<p>道路小修：'
                                        + (text[parseInt(time.slice(5, 7))].rep || 0) + '处</p><p>道路保养：'
                                        + (text[parseInt(time.slice(5, 7))].fit || 0)  + '处</p>'
                                        + '<p>道路病害：' + (text[parseInt(time.slice(5, 7))].dis || 0)  + '处</p>';
                                    k == parseInt(time) && _test[parseInt(time.slice(5, 7))].features.push(features[i]);
                                }
                            }
                            data.that._test[k] = _test;
                            mon = mon.sort(function (a, b) {
                                return a - b > 0;
                            });
                            _height = mon.length * 30;
                            y.push({
                                year: k,
                                month: mon,
                                height: _height || 60,
                                startLayout: idx === 0 ? h : h + 30 * idx + 20,
                                text: text
                            });
                            h += y[idx] && y[idx].height || 0;
                        }
                        idx += 1
                    }
                    renderData = {
                        time: y,
                        startM: startM,
                        height: h + "px",
                        numM: numM - 1
                    };
                    Message_bone.trigger("lifeShow", renderData);
                })
            }
        });
        Message_bone.on("query", function (e, data) {

            function hoverStyle(e) {
                if (e.dragging) {
                    return;
                }
                var pixel = map.getEventPixel(e.originalEvent);
                var hit = map.forEachLayerAtPixel(pixel, function() {
                    return true;
                },this,function(layer) {
                    if(layer.getSource().crossOrigin) return true;
                });
                map.getTargetElement().style.cursor = hit ? 'pointer' : 'default';
            }

            function hoverFeature(e) {
                if (e.dragging) {
                    return;
                }
                var pixel = map.getEventPixel(e.originalEvent);
                var hit = map.hasFeatureAtPixel(pixel);
                map.getTargetElement().style.cursor = hit ? 'pointer' : 'default';
            }

            function query(e) {
                var LAYERS = data.value["selector"] ? data.query + '_' + data.value["selector"]
                    : data.query;
                var s = data.roadName && "roadName=" + data.roadName;
                LAYERS += data.roadName && data.phase !== "规划" ? s : data.phase === "规划" ? "projectnam=" + data.roadName : "";
                if (data.roadName) {
                    var pixel = map.getEventPixel(e.originalEvent);
                    var hit = map.hasFeatureAtPixel(pixel);
                    data.query && $.ajax({
                        url: LAYERS
                    }).then(function (response) {
                        response = response[0] || response;
                        var feature = response && JSON.parse(response.geoJson).features;
                        if (hit) {
                            var overlay = new ol.Overlay({
                                element: document.getElementById("overlay"),
                                positioning: "bottom-center"
                            });
                            map.addOverlay(overlay);
                            var element = overlay.getElement();
                            $(element).addClass("detail");
                            $(element).find(".ohead p").html(response.projectname);
                            $(element).find(".ocontent").empty();
                            var property = feature[0].properties;
                            for (var key in property) {
                                if (typeof property[key] === "string" && key !== "projectId")
                                    $("<p>").text(Pengtu.buildCodeName("7777", key) + ": " + property[key]).appendTo($(element).find(".ocontent"));
                            }
                            $("<p>").text(Pengtu.buildCodeName("7777", "starttime") + ": " + response["starttime"]).appendTo($(element).find(".ocontent"));
                            $("<p>").text(Pengtu.buildCodeName("7777", "endtime") + ": " + response["endtime"]).appendTo($(element).find(".ocontent"));
                            if (data.phase === "前期") {
                                $("<p>").text("详细信息:").append($("<a>").text("查看详情").attr({
                                    "href": "/ssjc/pre/view/preparepoj!view.action?id=" + property["projectId"],
                                    "target": "_blank"
                                })).appendTo($(element).find(".ocontent"));
                                $(element).data("query", overlay);
                            } else {
                                $("<p>").text("详细信息:").append($("<a>").text("查看详情").attr({
                                    "href": "/ssjc/mp/view/project!view.action?id=" + property["projectId"],
                                    "target": "_blank"
                                })).appendTo($(element).find(".ocontent"));
                                $(element).data("query", overlay);
                            }
                            overlay.setPosition(e.coordinate);
                        } else {
                            var olay = $("#overlay").data("query");
                            olay && olay.setPosition([9999, 9999]);
                        }
                    });
                } else {
                    var params = {
                        REQUEST: "GetFeatureInfo",
                        EXCEPTIONS: "application/vnd.ogc.se_xml",
                        BBOX: map.getView().calculateExtent(map.getSize()).toString(),
                        SERVICE: "WMS",
                        INFO_FORMAT: 'application/vnd.ogc.gml',
                        QUERY_LAYERS: LAYERS,
                        FEATURE_COUNT: 50,
                        Layers: LAYERS,
                        WIDTH: map.getSize()[0],
                        HEIGHT: map.getSize()[1],
                        styles: "",
                        version: "1.1.1",
                        srs: "EPSG:900913",
                        crossOrigin:"anonymous",
                        x: parseInt(e.pixel[0]),
                        y: parseInt(e.pixel[1])
                    };
                    $.ajax({
                        url: data.url,
                        data: params,
                        beforeSend: function () {
                            Message_bone.trigger("infoStart");
                        }
                    }).then(function (response) {
                        var gml = new ol.format.GML();
                        var features = gml.readFeatures(response, 'EPSG:4326', 'EPSG:3857');
                        Message_bone.trigger("infoEnd");
                        if (features.length > 0) {
                            var overlay = new ol.Overlay({
                                element: document.getElementById("overlay"),
                                positioning: "bottom-center"
                            });
                            map.addOverlay(overlay);
                            var element = overlay.getElement();
                            $(element).css({
                                visibility: "visible"
                            });
                            $(element).find(".ocontent").empty();
                            $(element).removeClass("detail");
                            $(element).find("p").html(features[0].values_[data.queryName]);
                            Message_bone.trigger("showDetail", {
                                title: features[0].values_[data.queryName],
                                content: features[0].values_
                            });
                            Message_bone.trigger("search", features[0].values_[data.queryName]);
                            $(element).data("query", overlay);
                            overlay.setPosition(e.coordinate);

                            var pixel = map.getEventPixel(e.originalEvent);
                            var maxWidth = $("#mapContain").prop("clientWidth") - 100;
                            if (pixel[0] < 500 || pixel[0] > maxWidth || pixel[1] < 100) {
                                var coordinate;
                                var pan = new ol.animation.pan({
                                    duration: 800,
                                    easing: ol.easing.easeOut,
                                    source: map.getView().getCenter()
                                });
                                map.beforeRender(pan);
                                if (pixel[0] > maxWidth) {
                                    coordinate = map.getCoordinateFromPixel([$("#mapContain").prop("clientWidth") / 2 + 100, pixel[1]]);
                                    map.getView().setCenter(coordinate);
                                } else if (pixel[1] < 100) {
                                    coordinate = map.getCoordinateFromPixel([pixel[0], $("#mapContain").prop("clientHeight") / 2 - 100]);
                                    map.getView().setCenter(coordinate);
                                } else {
                                    map.getView().setCenter(e.coordinate);
                                }
                            }
                        } else {
                            var olay = $("#overlay").data("query");
                            olay && olay.setPosition([9999, 9999]);
                        }
                    })
                }
            }
            map.on('click', query);
            if(data.layer==="TileWMS"){
                map.on('pointermove', hoverStyle);
            }
            else if(data.layer==="WFS"||data.layer==="Vector"){
                map.on('pointermove', hoverFeature);
            }
            Message_bone.on("removeQuery", function () {
                map.un('click', query);
                map.un('pointermove', hoverStyle);
                map.un('pointermove', hoverFeature);
                var olay = $("#overlay").data("query");
                olay && olay.setPosition([9999, 9999]);
            });
        });

        $('#overlay').find('span.closeButton').click(function (e) {
            var olay = $("#overlay").data("query");
            olay && olay.setPosition([9999, 9999]);
        });

        return {
            map: map,
            szvector:szvector
        }
    }
});